
#include "my_net.h"
#include <asm-generic/errno-base.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
int main(int argc, char ** argv) {


  int j, fd, nchildren, nloops, nbytes;
  pid_t pid;
  ssize_t n;

  char request[1024], reply[1024];

  if (argc != 6) {

    printf("usage: client <hostname> <port> <#chlidren> <#loop/child> <#bytes/request>\n");
    return EXIT_FAILURE;
  }

  nchildren = atoi(argv[3]);
  nloops    = atoi(argv[4]);
  nbytes    = atoi(argv[5]);

  snprintf(request, 1024, "%d\n", nbytes);
  for (int child_index = 0; child_index < nchildren; child_index++) {

    if ((pid = fork()) == 0) {

      for (j = 0; j < nloops; j++) {

        fd = TcpConnect(argv[1], argv[2]);

        write(fd, request, strlen(request));
        if ((n = read(fd, reply, nbytes)) != nbytes) {

          printf("server returnd %ld bytes.\n", n);
          break;
        }
        printf("child %d done\n", child_index);
        exit(0);
      }
    }
    
  }
  while (wait(NULL) > 0) {
    ;
  }
  if (errno != ECHILD) {

    printf("wait error\n");
  }
  return EXIT_SUCCESS;
}
